import { Spin } from 'antd';
import classNames from 'classnames';
import { WeaLocaleProvider } from "ecCom";
import { toJS } from 'mobx';
import { inject, observer } from "mobx-react";
import React from "react";
import { viewTypes } from "../../../../constants/form";
import { generateSubComponents, propsComToViewCom } from "../component";
import FooterView from '../component/footer/View';
import { isDataTable } from "../component/typeof";
import ThemeContext from "../theme";
import FormMainView from "../view/Main";
import PreviewHeader from "./Header";
import { setComsValFromUrlParams } from '../../../../utils/setComsValFromUrlParams';
import "./index.less";
const getLabel = WeaLocaleProvider.getLabel;

const { PC, MOBILE } = viewTypes;
const { Provider } = ThemeContext;

@inject('routing', 'edcFormDesignerStore')
@observer
export default class FormPreview extends React.Component {
  constructor(props) {
    super();

    const { componentStore: store } = props.edcFormDesignerStore;

    this.store = store;
    this.state = {
      previewType: PC,
      loading: true,
      components: this.getComponents()
    };
  }

  componentDidMount() {
    if (this.store.components) {
      return this.setState({ loading: false });
    };

    const { params, edcFormDesignerStore } = this.props;

    this.setState({ loading: true });
    edcFormDesignerStore.init(params.appid).then(() => {
      this.setState({
        loading: false,
        components: this.getComponents()
      });
    });

  }

  onPreviewTypeChange = (previewType) => {
    this.setState({ previewType })
  }

  getComponents() {
    const components = toJS(this.store.components);
    let allComs = [];

    if (!components) return [];

    components.map(com => {
      const { title, complex, coms = [], widths } = com.config;

      com.config.name = title || '';

      allComs.push(com)

      if (complex) {
        const subComs = generateSubComponents(com);

        allComs.push(...subComs);
      }

      if (coms.length) {
        if (isDataTable(com)) {
          const newComs = coms.filter((com, index) => {
            if (com) return true;

            widths && widths.splice(index, 1);
          });

          allComs.push(...newComs);
        } else {

          allComs.push(...coms.filter(Boolean));

          coms.filter(Boolean).forEach(com => {
            if (com.config && com.config.complex) {
                const subComs = generateSubComponents(com);

                allComs.push(...subComs);
            }
          })
        }
      }
    });

    allComs = setComsValFromUrlParams(allComs);

    return allComs.map(propsComToViewCom);
  }

  onValueChange = (uuid, value) => {
    const { components } = this.state;
    const com = components.find(com => uuid === com.uuid);

    if (com.pid) {
      const pCom = components.find(c => com.pid === c.uuid);

      if (pCom.config.complex) {
        // work around 用于触发组件更新
        pCom.value = Math.random();
      }
    }

    com.value = value;

    this.setState({ components });
  }

  render() {
    const { previewType, components, loading } = this.state;
    const { formFooter, formHeader, footer, rightLevel, shortkey } = this.store;

    if (!components) return null;

    const { theme, joinCube } = this.props.edcFormDesignerStore;
    const { background } = theme;
    const isMobile = MOBILE === previewType;
    const clsNameStr = classNames('fp_main', {
      "wea-edc-fv-wrapper mobile-device": isMobile
    });

    return (
      <Provider ecId={`${this && this.props && this.props.ecId || ''}_Provider@dgin4n`} value={Object.assign({}, theme, joinCube)}>
        <div className='edc-form-preview'>
          <Spin ecId={`${this && this.props && this.props.ecId || ''}_Spin@g8gziw`} spinning={loading}>
            <PreviewHeader ecId={`${this && this.props && this.props.ecId || ''}_PreviewHeader@92yqw9`} onChange={this.onPreviewTypeChange} />
            <div className={`wea-edc-fp-wrapper fp_${previewType}`}
              style={background.css}
            >
              <div>
                <div className={clsNameStr}
                  style={isMobile ? background.css : {}}
                >
                  <FormMainView ecId={`${this && this.props && this.props.ecId || ''}_FormMainView@896vzx`}
                    formHeader={formHeader}
                    formFooter={formFooter}
                    components={components}
                    viewType={previewType}
                    onValueChange={this.onValueChange}
                  />
                  {
                    footer &&
                    <FooterView ecId={`${this && this.props && this.props.ecId || ''}_FooterView@s473e9`} data={footer.config} shortkey={rightLevel === 2 ? shortkey : ""} />
                  }
                  <div className='wea-edc-preview-warn'>
                    <label>{getLabel('513975', '预览不可操作提交数据')}</label>
                  </div>
                </div>
              </div>

            </div>
          </Spin>
        </div>
      </Provider>
    );
  }
}